package com.bigscreen.controller;

import com.bd1904.common.CommonUtil;
import com.bigscreen.service.TimeAmtService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

@ServerEndpoint("/web_socket/x_time")
@Controller
public class RealTimeTimeAmtWebSocket {
    @OnOpen
    public void onOpen(){
        System.out.println("建立连接");
    }
    @OnClose
    public void onClose(){
        System.out.println("关闭连接");
    }

    private static TimeAmtService taService;
    //websocket 需要通过方法注入
    @Autowired
    public void setTaService(TimeAmtService taService){
        RealTimeTimeAmtWebSocket.taService=taService;
    }

    @OnMessage
    public void onMessage(Session session){

        //推送到远程客户端
        while(true){
            try {
                String timeAmt = taService.timeAmt();
                session.getBasicRemote().sendText(timeAmt);

                CommonUtil.sleep(1000);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

}
